<!--这是产品详情组件-->
<template>
  <div class="createPost-container">
    <el-tabs v-model="activeName" type="border-card" style="height:30px;">
      <el-tab-pane v-for="item in tabMapOptions" :label="item.label" :key='item.key' :name="item.key" :disabled="!isEdit && item.enable">
      </el-tab-pane>
    </el-tabs>
    <el-form style="margin-top:40px;" :model="postForm" v-loading="formLoading" :rules="rules" ref="postForm" label-width="220px" label-position="right">
      <div v-show="activeName=='base'">
        <code v-if="!isEdit" style="width:800px;margin-left:20px;">
          <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
          必须按步骤填写。
        </code>
        <el-form-item label="产品名称：" prop="name">
          <el-input :maxlength="25" v-model="postForm.name" placeholder="请输入产品名称" style="width: 605px"></el-input>
          （不超过25个字）
        </el-form-item>
        <el-form-item label="产品介绍：" prop="introduce">
          <el-input :maxlength="50" v-model="postForm.introduce" placeholder="请输入产品介绍" style="width: 605px"></el-input>
          （不超过50个字）
        </el-form-item>
        <!-- <el-form-item label="所在地区：">
          <v-distpicker :province="postForm.provinceId" :city="postForm.cityId" :area="postForm.areaId" style="float: left;"></v-distpicker>
        </el-form-item> -->
        <el-form-item label="地址：">
          <areas :region="region" @reseviced="reseviced" :width="300" :level="2"></areas>
        </el-form-item>
        <el-form-item label="产品分类：">
          <el-row>
            <el-select clearable @change="catOnechange" style="width:300px;" v-model="postForm.catOne" placeholder="一级分类">
              <el-option v-for="item in categories" v-if="item.parentId==0" :key="item.gcId" :label="item.name" :value="item.gcId">
              </el-option>
            </el-select>
            <el-select clearable style="width:300px;"  v-model="postForm.catTwo" placeholder="二级分类">
              <el-option v-for="item in categories" v-if="item.parentId==catparId" :key="item.gcId" :label="item.name" :value="item.gcId">
              </el-option>
            </el-select>
          </el-row>
        </el-form-item>
        <el-form-item label="产品原价：">
          <el-input v-model="postForm.originalPrice" @keyup.native="postForm.originalPrice=isPrice(postForm.originalPrice)" placeholder="请输入产品原价" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
          （保留两位小数点，如开启规格，保存后自动同步第一个规格原价）
        </el-form-item>
        <el-form-item label="产品价格：" prop="price">
          <el-input v-model="postForm.price" @keyup.native="postForm.price=isPrice(postForm.price)" placeholder="请输入产品价格" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
          （保留两位小数点，如开启规格，保存后自动同步第一个规格价格）
        </el-form-item>
        <el-form-item label="积分可抵扣金额：">
          <el-input v-model="postForm.pointsDeduct" @keyup.native="postForm.pointsDeduct=isPrice(postForm.pointsDeduct)" placeholder="请输入积分可抵扣金额" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
          （保留两位小数点）
        </el-form-item>
        <!-- <el-form-item label="产品成本：">
          <el-input v-model="postForm.cost" placeholder="请输入产品成本" style="width: 650px"></el-input>
        </el-form-item> -->
        <el-form-item label="运费：">
          <el-input v-model="postForm.postage" @keyup.native="postForm.postage=isPrice(postForm.postage)" placeholder="请输入邮费" style="width: 300px">
            <template slot="append">元</template>
          </el-input>
          （保留两位小数点）
        </el-form-item>
        <el-form-item label="库存：">
          <el-input v-model="postForm.stock" @keyup.native="postForm.stock=isNum(postForm.stock)" placeholder="请输入库存" style="width: 300px">
            <template slot="append">件</template>
          </el-input>
          （如开启规格，保存后自动同步第一个规格库存）
        </el-form-item>
        <el-form-item label="虚拟已售数量：">
          <el-input v-model="postForm.initSales" @keyup.native="postForm.initSales=isNum(postForm.initSales)" placeholder="请输入" style="width: 300px">
            <template slot="append">件</template>
          </el-input>
        </el-form-item>
        <el-form-item label="实际已售数量：">
          <!-- {{postForm.sales}} -->
          <el-input :disabled="true" v-model="postForm.sales" placeholder="请输入" style="width: 300px">
            <template slot="append">件</template>
          </el-input>
          （用户看你到的已售数量=虚拟已售数量+实际已售数量）
        </el-form-item>
        <el-form-item label="是否热门：">
          <el-radio-group v-model="postForm.isHot">
            <el-radio v-for="item in isHotOptions" :key="item.id" :label="item.id" :value="item.id">{{item.value}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否新品：" style="color: red">
          <!-- <el-select v-model="postForm.isNew" placeholder="请选择" style="width: 300px">
            <el-option v-for="item in isNewOptions" :key="item.id" :label="item.value" :value="item.id"></el-option>
          </el-select> -->
          <el-radio-group v-model="postForm.isNew">
            <el-radio v-for="item in isNewOptions" :key="item.id" :label="item.id" :value="item.id">{{item.value}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="产品排序：">
          <el-input v-model="postForm.sort" placeholder="请输入产品排序" style="width: 300px"></el-input>（数值越大，排序越靠前）
        </el-form-item>
        <el-form-item label="是否开启邮箱：">
          <!-- <el-select v-model="postForm.isMail" placeholder="请选择" style="width: 300px">
            <el-option v-for="item in isMailOptions" :key="item.id" :label="item.value" :value="item.id"></el-option>
          </el-select> -->
          <el-radio-group v-model="postForm.isMail">
            <el-radio v-for="item in isMailOptions" :key="item.id" :label="item.id" :value="item.id">{{item.value}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否上架：">
          <!-- <el-select v-model="postForm.status" placeholder="请选择" style="width: 300px">
            <el-option v-for="item in isUpOptions" :key="item.id" :label="item.value" :value="item.id"></el-option>
          </el-select> -->
          <el-radio-group v-model="postForm.status">
            <el-radio v-for="item in isUpOptions" :key="item.id" :label="item.id" :value="item.id">{{item.value}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>
      <div v-show="activeName=='img'">
        <el-form-item label="上传图片(宽300*高300)：" prop="avatar">
          <el-upload style="float: left;"
            :action="URLAPI + '/common/goodsBanners/imageUpload'"
            list-type="picture-card"
            name="avatar"
            ref="avatarUpload"
            :before-upload="handleBeforeUpload"
            :on-success="handleAvatarSuccess"
            :on-remove="handleAvatarRemove"
            :file-list="postForm.banner"
            :limit="10"
            :auto-upload="true"
            :disabled="orderMgId ? true : false"
            :on-preview="handlePictureCardPreview">
            <i class="el-icon-plus"></i>
          </el-upload>
          <!-- <el-button style="margin-left: 10px;" size="small" type="success" @click="submitAvatarUpload">上传到服务器</el-button> -->
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="商品视频(MP4格式)：" prop="video">
          <el-upload
            class="upload-demo"
            name="file"
            :action="videoUploadUrl"
            :show-file-list="false"
            :data="formData"
            :before-upload="beforeVideoUpload"
            :on-success="handleVideoSuccess"
            :on-progress="uploadVideoProcess"
            drag>
            <video v-if="postForm.video && !videoFlag"  controls="controls" style="width:100%;height:100%;">
                <source :src="postForm.video" type="video/mp4">
                您的浏览器不支持视频播放。
            </video>
            <el-progress v-if="videoFlag" type="circle" :percentage="videoUploadPercent" style="margin-top:1.9rem"></el-progress>
            <template v-else>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将视频拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传MP4/文件，且不超过15MB（点击视频画面处可更换视频）</div>
            </template>
          </el-upload>
         </el-form-item>
      </div>
      <div v-show="activeName=='nature'" style="padding: 0px 45px 20px 50px;">
        <div style="margin-bottom:20px;">如洗衣机示例：</div>
        <table style="margin-left:50px;border:1px solid #d8dce5;border-radius:5px;margin-bottom:10px;padding: 5px 0;">
          <tr style="font-size:16px;color:#5a5e66;">
            <th style='width:300px'>名 称</th><th style='width:300px'>属性值</th>
          </tr>
          <tr>
            <td style="text-align:center;">证书编号</td><td style="text-align:center;">XXXXXXXXXX</td>
          </tr>
          <tr>
            <td style="text-align:center;">产品名称</td><td style="text-align:center;">滚筒全自动洗衣机</td>
          </tr>
          <tr>
            <td style="text-align:center;">能效等级</td><td style="text-align:center;">一级</td>
          </tr>
        </table>
        <table style="margin-left:50px;line-height:50px;">
          <tr style="font-size:16px;color:#5a5e66;">
            <th style='width:300px'>名 称</th><th style='width:300px'>属性值</th><th></th>
          </tr>
          <tr v-for="(item, index) in postForm.attributes">
            <td style="text-align:center;">
              <el-input v-model="postForm.attributes[index].k" placeholder="请输入" style='width:300px'></el-input>
            </td>
            <td style="text-align:center;">
              <el-input v-model="postForm.attributes[index].v" placeholder="请输入" style='width:300px'></el-input>
            </td>
            <td>
              <div @click="delEle(index)" style="width:40px;height:40px;text-align:center;cursor:pointer;">
                <i style="color:#ff4949;font-size:20px;" class="el-icon-delete"></i>
              </div>
            </td>
          </tr>
          <tr class="tr">
            <td style="text-align:center;" colspan="3">
              <el-button @click="addEle" class="filter-item" type="primary">添 加</el-button>
            </td>
          </tr>
        </table>
      </div>
      <div v-show="activeName=='spec'" style="padding: 0px 45px 20px 50px;">
        <specExample></specExample>
        <el-form-item label="开启规格：" label-width="120px">
          <el-switch v-model="postForm.specificationEnabled"></el-switch>
        </el-form-item>
        <div v-show="postForm.specificationEnabled">
          <div v-for="(item, index) in postForm.specs" class="spec">
            <el-form-item :label="'规格名称' + (index == 0 ? '（如颜色）：' : (index == 1 ? '（如产地）：' : '：'))" class="postInfo-container-item">
              <el-input :maxlength="20" v-model="postForm.specs[index].name" style='width:300px;'></el-input>
              <span @click="delSpec(index, index, 1)" class="delCoin"><i class="el-icon-delete"></i></span>
              <el-button @click="addSpecItem(index)" type="primary" size="mini">添加子规格项</el-button>
            </el-form-item>
            <el-form-item :label="'子规格项' + (index == 0 ? '（如红色）：' : (index == 1 ? '（如福建）：' : '：'))" class="postInfo-container-item">
              <span v-for="(vo, voindex) in postForm.specItems" v-if="(vo.gsId && vo.gsId == item.gsId) | vo.index == index" style="margin-right:50px;">
                <input :maxlength="20" v-model="postForm.specItems[voindex].name" class="specItem">
                <span class="delCoin" v-if="postForm.specItems.filter(specItem => (specItem.gsId && specItem.gsId == item.gsId) || specItem.index == index).indexOf(vo) != 0" @click="delSpec(index, voindex, 2)" ><i class="el-icon-delete"></i></span>
                <span class="delWhite" v-else><i class="el-icon-delete"></i></span>
              </span>
            </el-form-item>
          </div>
          <el-form-item label-width="80px" label="" class="postInfo-container-item">
            <el-button @click="addSpec" type="primary" size="max">添加规格</el-button>
          </el-form-item>
          <div v-if="postForm.specs.length">
            <table border="1" cellspacing="0" class="specInfos">
              <tr style="font-size:15px;color:#5a5e66;">
                <th v-for="item in postForm.specs">{{item.name}}</th><th>库存</th><th>原价</th><th>现价</th>
              </tr>
              <template v-if="postForm.specs.length==1"
              v-for="(item, index) in postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[0].gsId) | ite.index == 0)">
                <tr>
                  <td>{{item.name}}<span style="display:none">{{name = [item.name]}}</span><input style="display:none" v-model="postForm.specItemInfos[index].itemGroup=name"></td>
                  <td><input v-model="postForm.specItemInfos[index].stock" @keyup="postForm.specItemInfos[index].stock=isNum(postForm.specItemInfos[index].stock)"></td>
                  <td><input v-model="postForm.specItemInfos[index].originalPrice" @keyup="postForm.specItemInfos[index].originalPrice=isPrice(postForm.specItemInfos[index].originalPrice)"></td>
                  <td><input v-model="postForm.specItemInfos[index].price" @keyup="postForm.specItemInfos[index].price=isPrice(postForm.specItemInfos[index].price)"></td>
                </tr>
              </template>
              <template v-if="postForm.specs.length==2"
              v-for="(item, index) in postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[0].gsId) | ite.index == 0)">
                <template
                v-for="(vo, voindex) in postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1)">
                  <tr>
                    <td v-if="voindex%postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length == 0" :rowspan="postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length">{{item.name}}</td>
                    <td>{{vo.name}}<span style="display:none">{{name = [item.name,vo.name]}}</span><input style="display:none" v-model="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].itemGroup=name"></td>
                    <td><input @keyup="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].stock=isNum(postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].stock)" v-model="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].stock"></td>
                    <td><input @keyup="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].originalPrice=isPrice(postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].originalPrice)" v-model="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].originalPrice"></td>
                    <td><input @keyup="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].price=isPrice(postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].price)" v-model="postForm.specItemInfos[index * postForm.specItems.filter(ite => (ite.gsId && ite.gsId == postForm.specs[1].gsId) | ite.index == 1).length + voindex].price"></td>
                  </tr>
                </template>
              </template>
            </table>
          </div>
        </div>
      </div>
      <div v-show="activeName=='desc'">
        <el-form-item label="商品详情">
          <tinymce :height="500" v-model="postForm.desc" style="width: 800px;"></tinymce>
        </el-form-item>
        <el-form-item label="商品目录">
          <tinymce :height="500" v-model="postForm.catalog" style="width: 800px;"></tinymce>
        </el-form-item>
      </div>
      <div v-show="activeName=='tag'" style="padding: 0px 45px 20px 50px;">
        <el-checkbox-group v-if="tags.length > 0" v-model="postForm.tags" style="padding: 10px 20px;">
          <el-checkbox v-for="item in tags" :label="item.gtId" :key="item.gtId" style="margin-left:0;margin-right:30px;line-height:40px;">
            {{item.name}}
          </el-checkbox>
        </el-checkbox-group>
        <!-- <div v-else>无产品标签可选，请先到“商城管理->商城基础资料->商品标签”添加商品标签！</div> -->
        <code v-else style="width:800px;margin-left:20px;">
          <svg-icon icon-class="message" style="margin-right:10px;color:red;font-size:20px;"></svg-icon>
         无产品标签可选，请先到“商城管理->商城基础资料->商品标签”添加商品标签！
        </code>
      </div>
      <div v-show="activeName=='dis'">
        <el-form-item label="启用佣金比例：">
          <!-- <el-select v-model="postForm.distributionEnabled" clearable placeholder="请选择" style="width: 650px">
            <el-option v-for="item in isUseOptions" :key="item.id" :label="item.value" :value="item.id"></el-option>
          </el-select> -->
          <el-radio-group v-model="postForm.distributionEnabled">
            <el-radio v-for="item in isUseOptions" :key="item.id" :label="item.id" :value="item.id">{{item.value}}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="第一级抽成比例(单位%)：" prop="levelDistributionRatio1">
          <el-input v-model="postForm.levelDistributionRatio1" placeholder="请输入第一级抽成比例" style="width:650px" @keyup.native="postForm.levelDistributionRatio1=isPrice(postForm.levelDistributionRatio1)"></el-input>
        </el-form-item>
        <el-form-item label="第二级抽成比例(单位%)：" prop="levelDistributionRatio2">
          <el-input v-model="postForm.levelDistributionRatio2" placeholder="请输入第二级抽成比例" style="width: 650px" @keyup.native="postForm.levelDistributionRatio2=isPrice(postForm.levelDistributionRatio2)"></el-input>
        </el-form-item>
        <el-form-item label="第三级抽成比例(单位%)：" prop="levelDistributionRatio3">
          <el-input v-model="postForm.levelDistributionRatio3" placeholder="请输入第三级抽成比例" style="width: 650px" @keyup.native="postForm.levelDistributionRatio3=isPrice(postForm.levelDistributionRatio3)"></el-input>
        </el-form-item>
        <el-form-item label="代理商抽成比例(单位%)：" prop="agentRatio" v-if="this.agentLevel > 0">
          <el-input v-model="postForm.agentRatio" placeholder="代理商抽成比例" style="width: 650px" @keyup.native="postForm.agentRatio=isPrice(postForm.agentRatio)"></el-input>
        </el-form-item>
        <el-form-item label="合伙人抽成比例(单位%)：" prop="partnerRatio" v-if="this.agentLevel > 1">
          <el-input v-model="postForm.partnerRatio" placeholder="合伙人抽成比例" style="width: 650px" @keyup.native="postForm.partnerRatio=isPrice(postForm.partnerRatio)"></el-input>
        </el-form-item>
        <el-form-item label="分公司抽成比例(单位%)：" prop="branchRatio" v-if="this.agentLevel > 1">
          <el-input v-model="postForm.branchRatio" placeholder="分公司抽成比例" style="width: 650px" @keyup.native="postForm.branchRatio=isPrice(postForm.branchRatio)"></el-input>
        </el-form-item>
      </div>

      <el-form-item v-if="!orderMgId">
        <!-- <el-button type="primary" @click="preTag">上一步</el-button> -->
        <el-button type="primary" v-if="!isEdit && activeName != tabMapOptions[tabMapOptions.length - 1].key" @click="nextTag">下一步</el-button>
        <el-button type="primary" v-show="activeName=='tag' && tags.length > 0 || activeName!='tag'" v-if="isEdit | activeName == tabMapOptions[tabMapOptions.length - 1].key" v-loading="btnLoading" icon="el-icon-check" @click="submitForm">保存</el-button>
        <!-- <el-button type="info">取消</el-button> -->
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import VDistpicker from 'v-distpicker' // 引入城市选择器插件
import Tinymce from '@/components/Tinymce'
import { getGoodsDetail, goodSave, delImg } from '@/api/goods'
import { validateNumber, validatePrice } from '@/utils/validate'
import { validatePercent } from '@/utils/vm'
import { getAgentLevels } from '@/utils/permission'
import { getQiniuToken } from '@/api/qiniu'

const postForm = {
  mgId: null,
  companyId: null,
  cId: null,
  name: null,
  avatar: null,
  video:null,
  banner: [],
  originalPrice: null,
  price: null,
  cost: null,
  stock: null,
  postage: 0,
  initSales: 0,
  sales: 0,
  desc: null,
  provinceId: null,
  cityId: null,
  areaId: null,
  isHot: -1,
  isNew: -1,
  isInvoice: -1,
  isMail: -1,
  distributionEnabled: -1,
  levelDistributionRatio1: null,
  levelDistributionRatio2: null,
  levelDistributionRatio3: null,
  agentRatio: null,
  partnerRatio: null,
  branchRatio: null,
  pointsDeduct: 0,
  sort: 0,
  status: 1,
  catOne: null,
  catTwo: null,
  specificationEnabled: false,
  specs: [],
  specItems: [],
  specItemInfos: [],
  attributes: [],
  tags: []
}
const tabMapOptions = [
  { label: '基础信息', key: 'base', enable: false },
  { label: '产品图片', key: 'img', enable: true },
  { label: '产品属性', key: 'nature', enable: true },
  { label: '产品规格', key: 'spec', enable: true },
  { label: '产品详情', key: 'desc', enable: true },
  { label: '产品标签', key: 'tag', enable: true },
  // { label: '抽成设置', key: 'dis', enable: true }
]
const isMailOptions = [
  { id: 1, value: '是' },
  { id: -1, value: '否' }
]
const isHotOptions = [
  { id: 1, value: '是' },
  { id: -1, value: '否' }
]
const isNewOptions = [
  { id: 1, value: '是' },
  { id: -1, value: '否' }
]
const isUpOptions = [
  { id: 1, value: '是' },
  { id: -1, value: '否' }
]
const isUseOptions = [
  { id: 1, value: '是' },
  { id: -1, value: '否' }
]
const title = {
  name: '产品名称',
  price: '价格',
  avatar: '产品图片'
}
export default {
  components: {
    VDistpicker,
    Tinymce,
    areas: require('../../../areas/areas').default, // 引入地址
    specExample: require('./specExample').default
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    orderMgId: {
      type: Number,
      default: 0
    }
  },
  data() {
    const must = (rule, value, callback) => {
      if (!value) {
        this.$message({
          message: title[rule.field] + '必填！',
          type: 'error'
        })
        if (rule.field == 'name' | rule.field == 'price') {
          this.activeName = 'base'
        }
      } else {
        callback()
      }
    }
    const mustImg = (rule, value, callback) => {
      if (this.postForm.banner.length == 0) {
        this.$message({
          message: title[rule.field] + '必须至少上传一张！',
          type: 'error'
        })
        this.activeName = 'img'
      } else {
        callback()
      }
    }
    const validateSort = (rule, value, callback) => {
      if (value && isNaN(value) || value < 0) {
        callback('请输入正确的数值, 数值必须大于等于0')
      } else {
        callback()
      }
    }
    return {
      agentLevel: 0,
      postForm: Object.assign({}, postForm),
      region: { provinceId: null, cityId: null, areaId: null },
      dialogVisible: false,
      dialogImageUrl: null,
      activeName: 'base',
      isMailOptions,
      isHotOptions,
      isNewOptions,
      isUpOptions,
      isUseOptions,
      formLoading: false,
      btnLoading: false,
      URLAPI: process.env.BASE_API,
      tabMapOptions,
      catparId: null,
      categories: [],
      tags: [],
      rules: {
        name: [{ required: true, trigger: 'submitForm', validator: must }],
        price: [{ required: true, trigger: 'submitForm', validator: must }],
        avatar: [{ required: true, trigger: 'submitForm', validator: mustImg }],
        sort: [{ type: 'number', trigger: 'blur', validator: validateSort }],
        levelDistributionRatio1: [
          { type: 'number', validator: validatePercent, trigger: 'blur' }
        ],
        levelDistributionRatio2: [
          { type: 'number', validator: validatePercent, trigger: 'blur' }
        ],
        levelDistributionRatio3: [
          { type: 'number', validator: validatePercent, trigger: 'blur' }
        ],
        agentRatio: [
          { type: 'number', validator: validatePercent, trigger: 'blur' }
        ],
        partnerRatio: [
          { type: 'number', validator: validatePercent, trigger: 'blur' }
        ],
        branchRatio: [
          { type: 'number', validator: validatePercent, trigger: 'blur' }
        ]
      },
      videoUploadUrl: 'http://upload-z2.qiniup.com',
      formData: {
          token: null
          // key: null
      },
      baseUrl: '',
      videoFlag:false,
      videoUploadPercent:0.0,
    }
  },
  watch: {
    '$route': function(newData, oldData) {
      this.postForm = Object.assign({}, postForm)
      this.postForm = postForm
      this.postForm.banner = []
      this.postForm.specs = []
      this.postForm.specItems = []
      this.postForm.specItemInfos = []
      this.postForm.attributes = []
      this.postForm.tags = []
      this.tabMapOptions.forEach((element, index) => {
        this.tabMapOptions[index].enable = index != 0
      })
      this.region.provinceId = null
      this.region.cityId = null
      this.region.areaId = null
      this.postForm.catOne = null
      this.postForm.desc = null
      // if (newData != oldData) {
      this.getData()
      // }
    }
  },
  created() {
    this.getData();
    this.getToken();
    this.agentLevel = getAgentLevels()
  },
  methods: {
    getToken() {
        getQiniuToken().then(res => {
          this.formData.token = res.data.data.token;
          this.baseUrl = res.data.data.baseUrl;
        }).catch(err => {
          console.log(err)
        })
    },
    getData() {
      this.activeName = 'base'
      var mgId = this.$route.params.productId ? this.$route.params.productId : 0
      // 订单点击查看商品
      if (this.orderMgId) {
        mgId = this.orderMgId
      }
      console.log('添加商品-mgId:', mgId)
      if (mgId == 0) {
        this.postForm = Object.assign({}, postForm)
        this.postForm = postForm
        this.postForm.banner = []
        this.postForm.specs = []
        this.postForm.specItems = []
        this.postForm.specItemInfos = []
        this.postForm.attributes = []
        this.postForm.tags = []
        this.tabMapOptions.forEach((element, index) => {
          this.tabMapOptions[index].enable = index != 0
        })
        this.postForm.name = null
        this.postForm.avatar = null
        this.postForm.video = null
        this.postForm.originalPrice = null
        this.postForm.price = null
        this.postForm.cost = null
        this.postForm.stock = null
        this.postForm.postage = 0
        this.postForm.initSales = 0
        this.postForm.sales = 0
        this.postForm.desc = null
        this.postForm.provinceId = null
        this.postForm.cityId = null
        this.postForm.areaId = null
        this.postForm.isHot = -1
        this.postForm.isNew = -1
        this.postForm.isInvoice = -1
        this.postForm.isMail = -1
        this.postForm.distributionEnabled = -1
        this.postForm.levelDistributionRatio1 = null
        this.postForm.levelDistributionRatio2 = null
        this.postForm.levelDistributionRatio3 = null
        this.postForm.agentRatio = null
        this.postForm.partnerRatio = null
        this.postForm.branchRatio = null
        this.postForm.pointsDeduct = 0
        this.postForm.sort = 0
        this.postForm.status = 1
        this.postForm.catOne = null
        this.postForm.catTwo = null
        this.postForm.specificationEnabled = false
      }
      getGoodsDetail(mgId).then(res => {
        // if (this.$route.params.productId) {
        if (mgId) {
          this.postForm = res.data.data.goods
          this.region.provinceId = this.postForm.provinceId
          this.region.cityId = this.postForm.cityId
          this.region.areaId = this.postForm.areaId
          this.postForm.banner = res.data.data.banner.length > 0 ? res.data.data.banner : []
          this.postForm.specificationEnabled = res.data.data.goods.specificationEnabled == 1
          this.postForm.specs = res.data.data.goods.specs.length > 0 ? res.data.data.goods.specs : []
          this.postForm.specItems = res.data.data.goods.specItems.length > 0 ? res.data.data.goods.specItems : []
          this.postForm.specItemInfos = res.data.data.goods.specItemInfos.length > 0 ? res.data.data.goods.specItemInfos : []
          this.postForm.attributes = this.postForm.attributes ? this.postForm.attributes : []
          this.postForm.tags = this.postForm.tags ? this.postForm.tags : []
          if (this.postForm.catOne) {
            this.catparId = this.postForm.catOne
          }
        }
        this.categories = res.data.data.categories
        this.tags = res.data.data.tags
      }).catch(err => {
        console.log(err)
      })
    },
    nextTag() {
      if (this.activeName == 'base') {
        if (!this.postForm.name) {
          this.showMsg('产品名称必填！')
          return
        }
        if (!this.postForm.price) {
          this.showMsg('产品价格必填！')
          return
        }
        if (this.postForm.sort < 0 || isNaN(this.postForm.sort)) {
          this.showMsg('请输入正确的排序！')
          return
        }
      }
      if (this.activeName == 'img') {
        if (this.postForm.banner.length == 0) {
          this.showMsg('产品图片至少上传一张！')
          return
        }
      }
      console.log('保存的规格', postForm.specs.length)
      if (this.activeName == 'spec') {
        // 验证产品规格是否必填
        if (this.postForm.specificationEnabled && postForm.specs.length == 0) {
          this.showMsg('开启规格后请至少添加一个规格！')
          return
        }
      }
      var heldUp = false
      this.postForm.specs.forEach(element => {
        if (!element.name) {
          heldUp = true
          return
        }
      })
      this.postForm.specItems.forEach(element => {
        if (!element.name) {
          heldUp = true
          return
        }
      })
      this.postForm.specItemInfos.forEach(element => {
        if (element.stock === null || !element.originalPrice || !element.price) {
          heldUp = true
          return
        }
      })
      if (this.postForm.specificationEnabled && heldUp) {
        this.$message({
          type: 'error',
          message: '规格填写不完整！'
        })
        this.activeName = 'spec'
        return
      }

      this.activeName = this.tabMapOptions[this.tabMapOptions.indexOf(this.tabMapOptions.find(item => item.key == this.activeName)) + 1].key
      this.tabMapOptions.find(item => item.key == this.activeName).enable = false
    },
    showMsg(msg = '错误！', type = 'warning') {
      this.$message({
        message: msg,
        type: type
      })
    },
    catOnechange(val) {
      this.catparId = val || null
      this.postForm.catTwo = null
    },
    reseviced(data) {
      this.postForm.provinceId = data.provinceId
      this.postForm.cityId = data.cityId
      this.postForm.areaId = data.areaId
    },
    addSpec() {
      if (this.postForm.specs.length == 2) {
        this.$message({
          message: '最多添加两个',
          type: 'warning',
          duration: 3000
        })
        return false
      }
      this.postForm.specs.push({ gsId: null, mgId: this.postForm.mgId, name: null })
      this.postForm.specItems.push({ gsiId: null, mgId: null, gsId: null, name: null, index: this.postForm.specs.length - 1 })
      if (this.postForm.specs.length == 1) {
        this.postForm.specItemInfos.push({ gsiiId: null, mgId: null, itemGroup: [], stock: null, originalPrice: null, price: null })
      }
    },
    addSpecItem(index) {
      this.postForm.specItems.push({ gsiId: null, mgId: null, gsId: null, name: null, index: index })
      var num = 1
      this.postForm.specs.forEach((element, elIndex) => {
        num *= this.postForm.specItems.filter(item => (item.gsId && item.gsId == element.gsId) || item.index == elIndex).length
      })
      for (var i = this.postForm.specItemInfos.length; i < num; i++) {
        this.postForm.specItemInfos.push({ gsiiId: null, mgId: null, itemGroup: [], stock: null, originalPrice: null, price: null })
      }
    },

    delSpec(index, itemIndex, type) {
      var operation = this.postForm.specItems.filter(item => (item.gsId && item.gsId == this.postForm.specs[index].gsId) || item.index == index)
      if (type == 1) {
        this.postForm.specs.splice(index, 1)
        operation.forEach(element => {
          this.postForm.specItems.splice(this.postForm.specItems.indexOf(element), 1)
        })
        this.postForm.specItemInfos = []
        for (var i = 0; i < this.postForm.specItems.length; i++) {
          this.postForm.specItemInfos.push({ gsiiId: null, mgId: null, itemGroup: [], stock: null, originalPrice: null, price: null })
        }
      }
      if (type == 2) {
        var newIndex = operation.indexOf(this.postForm.specItems[itemIndex])
        if (this.postForm.specs.length == 2) {
          var specItemOne = this.postForm.specItems.filter(item => (item.gsId && item.gsId == this.postForm.specs[0].gsId) || item.index == 1)
          var specItemTwo = this.postForm.specItems.filter(item => (item.gsId && item.gsId == this.postForm.specs[1].gsId) || item.index == 1)
          if (index == 0) {
            this.postForm.specItemInfos.splice(specItemTwo.length * newIndex, specItemTwo.length)
          }
          if (index == 1) {
            for (var i = specItemOne.length * specItemTwo.length - (specItemTwo.length - newIndex); i >= newIndex; i -= specItemTwo.length) {
              this.postForm.specItemInfos.splice(i, 1)
            }
          }
        }
        if (this.postForm.specs.length == 1) {
          this.postForm.specItemInfos.splice(itemIndex, 1)
        }
        this.postForm.specItems.splice(itemIndex, 1)
      }
    },
    isNum(field) {
      return validateNumber(field)
    },
    isPrice(field) {
      return validatePrice(field)
    },
    addEle() {
      this.postForm.attributes.push({ k: null, v: null })
    },
    delEle(index) {
      this.postForm.attributes.splice(index, 1)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          var heldUp = false
          this.postForm.specs.forEach(element => {
            if (!element.name) {
              heldUp = true
              return
            }
          })
          this.postForm.specItems.forEach(element => {
            if (!element.name) {
              heldUp = true
              return
            }
          })
          this.postForm.specItemInfos.forEach(element => {
            if (element.stock === null || !element.price) {
              heldUp = true
              return
            }
          })
          this.postForm.specItemInfos.forEach(element => {
            if (!element.originalPrice) {
              element.originalPrice = 0
            }
          })
          if (this.postForm.specificationEnabled && heldUp) {
            this.$message({
              type: 'error',
              message: '规格填写不完整！'
            })
            this.activeName = 'spec'
            return
          }
          if (this.postForm.pointsDeduct - this.postForm.price > 0) {
            this.$message({
              type: 'error',
              message: '积分最高抵扣不能大于产品价格！'
            })
            this.activeName = 'base'
            return
          }
          if (this.postForm.levelDistributionRatio1 < 0 || this.postForm.levelDistributionRatio2 < 0 || this.postForm.levelDistributionRatio3 < 0 || this.postForm.agentRatio < 0 || this.postForm.partnerRatio < 0 || this.postForm.branchRatio < 0) {
            this.$message({
              message: '抽成比例不能为负数',
              type: 'error'
            })
            return
          }
          if (this.postForm.levelDistributionRatio1 > 100 || this.postForm.levelDistributionRatio2 > 100 || this.postForm.levelDistributionRatio3 > 100 || this.postForm.agentRatio > 100 || this.postForm.partnerRatio > 100 || this.postForm.branchRatio > 100) {
            this.$message({
              message: '抽成比例不能大于100',
              type: 'error'
            })
            return
          }
          if (this.postForm.levelDistributionRatio1 == 0) {
            if (this.postForm.levelDistributionRatio2 != 0 || this.postForm.levelDistributionRatio3 != 0) {
              this.$message({
                message: '第一级抽成比例为0，第二三级也只能为0',
                type: 'error'
              })
              return
            }
          }
          if (this.postForm.levelDistributionRatio2 == 0) {
            if (this.postForm.levelDistributionRatio3 != 0) {
              this.$message({
                message: '第二级抽成比例为0，第三级也只能为0',
                type: 'error'
              })
              return
            }
          }
          if (Number(this.postForm.levelDistributionRatio1) + Number(this.postForm.levelDistributionRatio2) + Number(this.postForm.levelDistributionRatio3) + Number(this.postForm.agentRatio) + Number(this.postForm.partnerRatio) + Number(this.postForm.branchRatio) > 100) {
            this.$message({
              message: '一二三跟代理商、合伙人、分公司抽成比例总和不能大于100',
              type: 'error',
              align: 'center'
            })
            return
          }

          const emptyAttributes = this.postForm.attributes.filter(item => {
            return (item.k == null && item.v != null) || (item.k != null && item.v == null)
          })
          if (emptyAttributes.length > 0) {
            this.$message({
              message: '属性和属性值必须同时不为空',
              type: 'error',
              align: 'center'
            })
            return
          }

          this.postForm.attributes = this.postForm.attributes.filter(item => {
            return item.k != null && item.v != null
          })

          var data = { data: this.postForm }
          // 验证产品规格是否必填
          if (this.postForm.specificationEnabled && this.postForm.specs.length == 0) {
            this.showMsg('开启规格后请至少添加一个规格！')
            this.activeName = 'spec'
            return
          }
          if (this.btnLoading) {
            return
          }
          this.btnLoading = true
          goodSave(data).then(res => {
            // this.postForm.mgId = res.data.data
            this.btnLoading = false
            this.$message({
              type: 'success',
              message: '保存成功！'
            })
            this.close()
          }).catch(err => {
            console.log(err)
          })
        } else {
          this.$message({
            type: 'error',
            message: '提交失败！'
          })
          return false
        }
      })
    },
    handleAvatarRemove(file, fileList) {
      this.postForm.banner.splice(this.postForm.banner.indexOf(file), 1)
      var data = { imgUrl: file.url }
      delImg(data).then(res => {
        // console.log(res)
      }).catch(err => {
        console.log(err)
      })
    },
    handleBeforeUpload(file) {
      const isImg = file.type == 'image/jpeg' || file.type == 'image/png'
      if (!isImg) {
        this.$message.warning('上传图片只能是 JPG 或 PNG 格式')
      }
      return isImg
    },
    submitAvatarUpload() {
      this.$refs.avatarUpload.submit()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleAvatarSuccess(file) {
      this.postForm.banner.push({ bId: null, mgId: null, url: file.data.imageUrl, sort: null })
    },
    //视频上传验证
    beforeVideoUpload(file){
      const isVideo = file.type === 'video/mp4';
      const isLt = file.size / 1024 / 1024 < 15;
      if (!isVideo) {
        this.$message.error('上传视频只能是 MP4 格式!');
      }
      if (!isLt) {
        this.$message.error('上传视频大小不能超过 15MB!');
      }
      return isVideo && isLt;
    },
    //视频上传成功
    handleVideoSuccess(res, file){
      if (res.key) {
        this.postForm.video = this.baseUrl+res.key
        this.$message({
          message: '上传成功!',
          type: 'success'
        })
      } else {
        this.$message.error('上传失败，请稍候再试!');
      }
      this.videoFlag = false;
    },
    //视频上传进度
    uploadVideoProcess(event, file, fileLis){
      this.videoFlag = true;
      this.videoUploadPercent = parseFloat(file.percentage.toFixed(1));
    },

    close() {
      this.$store.dispatch('delVisitedViews', this.$route).then((views) => {
        const latestView = views.slice(-1)[0]
        if (latestView != null && latestView != '') {
          // if (activeName == 'first') {
          this.$router.push({ path: '/mall/productList' })
          // }
        } else {
          this.$router.push('/')
        }
      })
    }
  }
}
</script>
<style scoped>
	.spec{
    border:1px solid #d8dce5;border-radius:5px;margin-bottom:10px;padding: 20px 0;
  }
  .delCoin{
    cursor:pointer;padding:5px;color:#ff4949;font-size:18px;
  }
  .delWhite{
    padding:5px;color:#fff;font-size:18px;
  }
  .specItem{
     width:200px;height:35px;border-radius:3px;margin-top:7px;border:1px solid #d8dce5;padding-left:10px;
  }
  .specInfos{
    width:100%;border-color:#eaeff0;text-align:center;
  }
  .specInfos tr{
    height:40px;
  }
  .specInfos tr>td input{
    width:70%;height:25px;
  }
  input {
    outline: none;
  }
</style>
